using Microsoft.AspNetCore.Mvc;
using SqlsugarService.Application.DTOs.QualityInspection;
using SqlsugarService.Application.Service.QualityInspection;
using SqlsugarService.Application.Until;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SqlsugarService.API.Controllers.QualityInspection
{
    /// <summary>
    /// 质检方案与报工质检关联控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class QualityInspectionPlanWorkReportController : ControllerBase
    {
        private readonly QualityInspectionPlanWorkReportService _service;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service">质检方案与报工质检关联服务</param>
        public QualityInspectionPlanWorkReportController(QualityInspectionPlanWorkReportService service)
        {
            _service = service;
        }

        #region 质检操作接口

        /// <summary>
        /// 质检操作：修改报工质检状态为已质检，并添加质检方案关联
        /// </summary>
        /// <param name="workReportInspectionId">报工质检Id</param>
        /// <param name="qualityInspectionPlanIds">质检方案Id列表</param>
        /// <returns>操作结果</returns>
        [HttpPost("process-quality-inspection")]
        public async Task<ApiResult<QualityInspectionOperationResultDto>> ProcessQualityInspection(
            [FromQuery] Guid workReportInspectionId,
            [FromBody] List<Guid> qualityInspectionPlanIds)
        {
            try
            {
                if (qualityInspectionPlanIds == null || qualityInspectionPlanIds.Count == 0)
                {
                    return ApiResult<QualityInspectionOperationResultDto>.Fail(
                        "质检方案Id列表不能为空", ResultCode.ValidationError);
                }

                var result = await _service.ProcessQualityInspectionAsync(
                    workReportInspectionId,
                    qualityInspectionPlanIds,
                    GetCurrentUserId());

                if (result.Code == ResultCode.Success && result.Data != null)
                {
                    return ApiResult<QualityInspectionOperationResultDto>.Success(
                        MapToDto(result.Data), ResultCode.Success);
                }
                return ApiResult<QualityInspectionOperationResultDto>.Fail(
                    result.Msg, result.Code);
            }
            catch (Exception ex)
            {
                return ApiResult<QualityInspectionOperationResultDto>.Fail(
                    $"服务器异常: {ex.Message}", ResultCode.Error);
            }
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 获取当前用户Id（示例实现）
        /// </summary>
        /// <returns>用户Id</returns>
        private string? GetCurrentUserId()
        {
            // 这里应该从JWT Token或Session中获取当前用户Id
            // 示例实现，实际项目中需要根据认证方式调整
            return User?.Identity?.Name ?? "system";
        }

        /// <summary>
        /// 将业务对象映射为DTO
        /// </summary>
        /// <param name="source">源对象</param>
        /// <returns>DTO对象</returns>
        private QualityInspectionOperationResultDto MapToDto(QualityInspectionOperationResult source)
        {
            return new QualityInspectionOperationResultDto
            {
                WorkReportInspectionId = source.WorkReportInspectionId,
                Status = source.Status,
                ProcessedAt = source.ProcessedAt,
                ProcessedBy = source.ProcessedBy,
                AddedAssociationsCount = source.AddedAssociationsCount,
                AssociationIds = source.AssociationIds
            };
        }

        #endregion
    }
}